package servlet;

import dao.NewDao;
import entity.New;
import entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/updateNew")
public class NewPrepareUpdateServlet extends HttpServlet {
	@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }
	@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		Integer id = Integer.parseInt(request.getParameter("id"));
		String author = request.getParameter("author");
		User user = (User) request.getSession().getAttribute("user");
		if(user.getRole() == 1 || user.getUserName().equals(author)){
			System.out.println("-----------/updateNew-----------");
			System.out.println(id);
			NewDao dao = new NewDao();
			New aNew = dao.selectNew(id);
			if (aNew != null) {
				request.setAttribute("aNew", aNew);
				request.getSession().setAttribute("update_newId", aNew.getId());
				System.out.println(aNew.getTitle());
				request.getRequestDispatcher("./update_new.jsp").forward(request, response);
			}else {
				response.sendRedirect("./newList");
			}
		}else {
			request.getSession().setAttribute("errorMsg", "暂无权限");
			System.out.println("暂无权限");
			request.getRequestDispatcher("./newList").forward(request, response);
			return;
		}
	}
}
